package com.example.qihuibao.utils

import com.example.qihuibao.XApplication
import com.example.qihuibao.bean.CheckNewVersionResponseBean
import com.example.qihuibao.bean.UpdateBean
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException

object FirUpdateUtil {
    const val ID = "654ccc66b2eb46670189d2fb"
    const val API_TOKEN = "21dec718aa6f5ef881e429cc5649852e"
    val apkDir = "${XApplication.application.getExternalFilesDir("")?.path}/"

    fun checkNewVersion(back:(bean:CheckNewVersionResponseBean)->Unit) {
        OkHttpClient().newCall(
            Request.Builder()
                .get()
                .url("http://api.bq04.com/apps/latest/$ID?api_token=$API_TOKEN")
                .build()
        ).enqueue(object: okhttp3.Callback {
            override fun onFailure(call: okhttp3.Call, e: IOException) {
                back(CheckNewVersionResponseBean())
            }

            override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                try {
                    val data = "${response.body()?.string()}"
                    val bean = Gson().fromJson(data, UpdateBean::class.java)
                    if (bean != null && (bean.version?.toInt() ?: 0) > SystemManagerUtils.getVersionCode()) {
                        back(CheckNewVersionResponseBean(hasNewVersion = true, version = bean.versionShort, apkUrl = bean.installUrl, message = bean.changelog))
                    }else {
                        back(CheckNewVersionResponseBean())
                    }
                }catch (e:Exception) {
                    back(CheckNewVersionResponseBean())
                }
            }
        })
    }
}